<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class Admin extends Controller
{
    //管理员列表
    public function index()
    {
        $data['admin']= DB::table('admin')->lists();
        return view('admin.admin.index',$data);
    }
    public function add(Request $request)
    {
        //获取前台传过来的ID
        $aid = $request->aid;
        //通过ID查询角色表中现在的角色名称
        $data['item'] = DB::table('admin')->where('id',$aid)->item();
        //渲染全部的角色
        $data['groups'] = DB::table('admin_group')->select('gid','title')->lists();
        return view('admin.admin.add',$data);
    }
    public function save(Request $request)
    {
        $aid = (int)$request->aid;
        $username = trim($request->username);
        $pwd = trim($request->pwd);
        $data['gid'] = (int)$request->gid;
        $data['nickname'] = trim($request->nickname);
        $data['phone'] = trim($request->phone);
        $data['status'] = $request->status=='on'?1:0;

        if($aid==0 && $username==''){
            exit(json_encode(array('code'=>1,'msg'=>'用户名不能为空')));
        }
        // 保存到数据库
        if($aid==0){
            $admin_user = DB::table('admin')->where('username',$username)->first();
            if($admin_user){
                exit(json_encode(array('code'=>1,'msg'=>'该帐号已存在')));
            }

            $data['username'] = $username;
            $data['password'] = password_hash($pwd,PASSWORD_DEFAULT);
            $data['add_time'] = time();
            DB::table('admin')->insert($data);
        }else{
            if($pwd){
                $data['password'] = password_hash($pwd,PASSWORD_DEFAULT);
            }
            DB::table('admin')->where('id',$aid)->update($data);
        }

        exit(json_encode(array('code'=>0,'msg'=>'保存成功')));
    }
}
